﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using log4net;

namespace iSufeMVC4.SufeAPI
{
    public class SufeSerive : OAuthBase, ISerive
    {
        ILog logger = LogManager.GetLogger(typeof(SufeSerive));
        
        public string getStudentInfo(string stdCode,string stdName){
        
            //StudentInfo
            var dictionary = new Dictionary<object, object>
            {
                {"std.code",stdCode},
                {"std.name",""},//stdName
                {"majorTypeId:",1},

            };
            string ReturnHtml = HttpPost(@"courseTablePublic.do?method=list", dictionary);
            return ReturnHtml;
        }
        /// <summary>
        /// 分析HTTP，创建CourseTable
        /// </summary>
        /// <param name="stdId"></param>
        /// <param name="calendarId"></param>
        /// <returns></returns>
        public StudentCourseTable getStudentCourseTable(int stdId, int calendarId)
        {

            //Get StudentCourseTable
            var dictionary = new Dictionary<object, object>
            {
                {"method","courseTable"},
                {"setting.kind","std"},
                {"setting.forCalendar",0},
                {"calendar.id",calendarId},
                {"ids",stdId}
            };
            string html = HttpGet(@"courseTablePublic.do", dictionary);

            StudentCourseTable result = new StudentCourseTable();
            result.CalendarId = calendarId;
            result.StdId = stdId;
            //CalendarName
            result.CalendarName = Regex.Match(html, @"<h3 \w+=""\w+"">(.*[^<])</h4>").Groups[1].Value;
            //StdName
            Match StdNameMatch = Regex.Match(html, @"Student Name:(\w+)|学生姓名:(\w+)");
            result.StdName = StdNameMatch.Groups[1].Value.Length>0?
                StdNameMatch.Groups[1].Value : StdNameMatch.Groups[2].Value;
            //StdCode
            Match StdCodeMatch = Regex.Match(html, @"Student No:(\w+)|学号:(\w+)");
            result.StdCode = StdCodeMatch.Groups[1].Value.Length>0?
                StdCodeMatch.Groups[1].Value : StdCodeMatch.Groups[2].Value;
            //AdminClassName
            Match AdminClassNameMatch=Regex.Match(html, @"With Admin Class: (\w+)|所属班级: (\w+)");
            result.AdminClassName = AdminClassNameMatch.Groups[1].Value.Length>0?
                AdminClassNameMatch.Groups[1].Value : AdminClassNameMatch.Groups[2].Value;
            //TotalCredits
            Match TotalCreditsMatch=Regex.Match(html, @"Total Credit:(\d+)|总学分:(\d+)");
            result.TotalCredits = Convert.ToInt32(TotalCreditsMatch.Groups[1].Value.Length>0?
                TotalCreditsMatch.Groups[1].Value : TotalCreditsMatch.Groups[2].Value);
            //Activity
            result.Activity = new List<CourseActivity>();
            MatchCollection activities = Regex.Matches(html, @"activity = new TaskActivity\(""(?<TeacherId>\d+)"",""(?<TeacherName>\w+)"",""(?<CourseId>\d+)\(\d+\)"",""(?<CourseName>.*?)\((?<SeqNo>\d+)\)"",""(?<ClassroomId>\d+)"",""(?<ClassroomName>\w+)"",""(?<ValidWeeks>\d+)""\);(\s*?index =(?<WeekDay>\d+)\*unitCount\+(?<Index>\d+);\s*? table0.activities\[index]\[table0.activities\[index]\.length]=activity;)+");
            foreach (Match match in activities)
            {
                CourseActivity act = new CourseActivity();
                act.TeacherId = Convert.ToInt32(match.Groups["TeacherId"].Value);
                act.TeacherName = match.Groups["TeacherName"].Value;
                act.CourseId = Convert.ToInt32(match.Groups["CourseId"].Value);
                act.CourseName = match.Groups["CourseName"].Value;
                act.SeqNo = Convert.ToInt32(match.Groups["SeqNo"].Value);
                act.ClassroomId = Convert.ToInt32(match.Groups["ClassroomId"].Value);
                act.ClassroomName = match.Groups["ClassroomName"].Value;
                act.ValidWeeks = match.Groups["ValidWeeks"].Value;
                act.CourseTime = new List<CourseActivityTime>();
                int count=match.Groups["WeekDay"].Captures.Count;
                for(int i=0;i<count;i++)
                {
                    act.CourseTime.Add(new CourseActivityTime(
                        Convert.ToInt32(match.Groups["WeekDay"].Captures[i].Value),
                        Convert.ToInt32(match.Groups["Index"].Captures[i].Value)));
                }
                result.Activity.Add(act);
            }
            //TaskBrief
            result.TaskBrief = new List<CourseTaskBrief>();
            MatchCollection TaskBriefs=Regex.Matches(html,@"<tr[^>]*>\s+<td>\d+[^0-9]*(?<CourseCode>\d+)</td>\s+[^0-9]*(?<TaskId>\d+)"" title=""[^>]*>(?<SeqNo>\d+)</a></td>\s*<td>(?<TeacherName>\w*)[^0-9]*[^>]*>\s*(?<CourseName>[^<]*)</a>\s*</td>[^>]*>(?<CourseType>[^<]*)[^0-9]*(?<WeekUnits>\d+)[^0-9]*(?<Credits>\d+)</td>\s*<td>(?<FirstLessonDate>[^<]*)</td>\s*<td>(?<IsPublic>[^<]*)</td>\s*<td>(?<CourseLangType>[^<]*)[^0-9]*(?<WeekStart>\d+)</td>\s*<td>(?<Comments>[^<]*)");
            foreach (Match match in TaskBriefs)
            {
                CourseTaskBrief task = new CourseTaskBrief();
                task.CourseCode = Convert.ToInt32(match.Groups["CourseCode"].Value);
                task.TaskId = Convert.ToInt32(match.Groups["TaskId"].Value);
                task.SeqNo = Convert.ToInt32(match.Groups["SeqNo"].Value);
                task.CourseName = match.Groups["CourseName"].Value;
                task.CourseType = match.Groups["CourseType"].Value;
                task.TeacherName = match.Groups["TeacherName"].Value;
                task.WeekUnits = Convert.ToInt32(match.Groups["WeekUnits"].Value);
                task.Credits = Convert.ToInt32(match.Groups["Credits"].Value);
                task.FirstLessonDate = match.Groups["FirstLessonDate"].Value;
                task.IsPublic = match.Groups["IsPublic"].Value;
                task.CourseLangType = match.Groups["CourseLangType"].Value;
                task.WeekStart = Convert.ToInt32(match.Groups["WeekStart"].Value);
                task.Comments = match.Groups["Comments"].Value;
                result.TaskBrief.Add(task);
            }
            return result;
        }

        #region Must
        #region Post
        public T HttpPost<T>(string partUrl, IDictionary<object, object> dictionary) where T : class
        {
            return HttpPost<T>(partUrl, dictionary, null);
        }

        public T HttpPost<T>(string partUrl, IDictionary<object, object> dictionary, byte[] file) where T : class
        {
            //dictionary.Add("access_token", base.Token.access_token);

            var url = base.baseUrl.ToFormat(partUrl);
            var query = dictionary.ToQueryString();
            logger.Error(url);
            logger.Error(query);
            var json = string.Empty;
            if (file != null)
            {
                json = base.HttpMethod.HttpPost(url, dictionary, file);
            }
            else
            {
                json = base.HttpMethod.HttpPost(url, query);
            }

            return json.ToEntity<T>();
        }

        public string HttpPost(string partUrl, IDictionary<object, object> dictionary)
        {
            //dictionary.Add("access_token", base.Token.access_token);

            var url = base.baseUrl.ToFormat(partUrl);
            var query = dictionary.ToQueryString();
            logger.Error(url);
            logger.Error(query);
            return base.HttpMethod.HttpPost(url, query);
        }
        #endregion

        #region Get
        public T HttpGet<T>(string partUrl, IDictionary<object, object> dictionary) where T : class
        {
            //dictionary.Add("access_token", base.Token.access_token);

            var url = base.baseUrl.ToFormat(partUrl);
            var query = dictionary.ToQueryString();
            logger.Error(url + "?" + query);
            var json = base.HttpMethod.HttpGet(url + "?" + query);
            return json.ToEntity<T>("json");
        }

        public string HttpGet(string partUrl, IDictionary<object, object> dictionary)
        {
            //dictionary.Add("access_token", base.Token.access_token);

            var url = base.baseUrl.ToFormat(partUrl);
            var query = dictionary.ToQueryString();
            logger.Error(url + "?" + query);
            return base.HttpMethod.HttpGet(url + "?" + query);
        }

        public string DirectHttpGet(string Url)
        {
            logger.Error(Url);
            return base.HttpMethod.HttpGet(Url);
        }
        #endregion
        #endregion
    }
}
